/**
 * OM分机服务
 *
 */
define(['app'], function( app ) {
    'use strict';

    app.factory('ext',  ['$q','$interval','dataFactoryCRM', function($q,$interval, dataFactoryCRM) {
        /*分机状态 -2:掉线;-1：未初始化；0：空闲；1、拨号中;2、通话中*/
        var ext = {state:-1,user_id:''/*用户ID*/,line_id:''/*分机线路编号*/,ext:''/*用户分机号*/,omid:''/*设备OM编号*/,ipaddr:''/*局域网代理服务器地址*/,
                        freetm:0/*空闲时间*/,ctime:0/*通话计时*/,area:'',phone:'',timerID:undefined,outer:false,visitor:false,_cdr:false
                  };

        ext.getCalls = function( ){
                var deferred = $q.defer();
                dataFactoryCRM.getDataByAPI('call/records').then( function( _d ){
                deferred.resolve( _d );
             }, function (error) {
                deferred.reject(error);
            });

            return deferred.promise;
        };

        //分机登陆成功
        ext.login = function(){
            ext.state = 0;
        };

        //分机掉线
        ext.offline = function(){
            ext.state = -2;
            ext.ctime = 0;
        };

        //分机登录局域网websocklet初始化
        ext.init = function( _d ){
            this.state = 0;
        };

        ext.cdr = function( d ){
            if( d ){
                this._cdr = {};
                this._cdr.ext = this.ext ;
                this._cdr.calltype =  (d['m_type'] == 'OU') ? '打出' : ( d['m_type'] == 'IN' ? "打入":"其他");
                this._cdr.telephone = d['m_cpn'] == this.ext ? d['m_cdpn'] : d['m_cpn'];
                this._cdr.calltime = d['m_duration'];
                this._cdr.begintime = d['tm'].substring(5);
            }
        };

        //拨打电话
        ext.call = function(phone, area ){
            this.state = 1;
            this.area = area;
            this.phone = phone;
        };

        //来电
        ext.incall = function( phone, area ){
            this.state = 1;
            this.area = area;
            this.phone = phone;
        };

        //挂断电话
        ext.hangup = function(){
            this.state = 0;
            this.area = '';
            this.phone = '';
            this.outer = false;
            this.visitor = false;
        };

        //接听电话
        ext.pickup = function(){
            this.state = 1;
        };



        return ext;
    }]);
});